import hashlib
from models.models.RequestResult import RequestResult as Res
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from models.models import SystemUser
from django.shortcuts import render
import json
import math


# 转发到系统用户管理页
def to_user(request):
    fields = SystemUser.get_fields()
    res = {
        "name": "管理员用户",
        "fields": fields,
        "selectValues": "",
        "getListUrl": "/admin/user/getList/",
        "getOneUrl": "/admin/user/getOne/",
        "insertUrl": "/admin/user/insert/",
        "updateUrl": "/admin/user/update/",
        "deleteUrl": "/admin/user/delete/"
    }
    return render(request, "storeAdmin/common/list.html", res)


# 获取用户列表
def get_user_list(request):
    page_number = request.GET.get("page_number")
    if page_number is None:
        page_number = 1
    else:
        page_number = int(page_number)
    page_size = 10
    limit = (page_number - 1) * page_size
    offset = limit+page_size
    count = 0
    users = []
    user_name = request.GET.get("user_name")
    if not user_name:
        users = SystemUser.objects.filter().order_by("-id")[limit:offset]
        count = SystemUser.objects.filter().count()
    else:
        users = SystemUser.objects.filter(user_name__contains=user_name).order_by("-id")[limit:offset]
        count = SystemUser.objects.filter(user_name__contains=user_name).count()
    page_total = math.ceil(count / page_size)
    res_users = []
    for user in users:
        res_user = dict()
        res_user["id"] = user.id
        res_user["user_name"] = user.user_name
        res_user["user_pass"] = user.user_pass
        res_user["nick_name"] = user.nick_name
        res_user["user_icon"] = user.user_icon
        res_users.append(res_user)
    res_date = dict()
    res_date["list"] = res_users
    res_date["page_number"] = page_number
    res_date["page_total"] = page_total
    return JsonResponse(Res.success(res_date))


# 获取某一管理员用户
def get_user_one(request):
    id = request.GET.get('id')
    user = SystemUser.objects.filter(id=id).first()
    return JsonResponse(user.to_dict())


# 新增用户
@csrf_exempt
def insert(request):
    user = SystemUser.objects.filter(user_name=request.POST.get("user_name")).first()
    if not user:
        user = SystemUser()
        user.user_name = request.POST.get("user_name")
        user.user_pass = hashlib.md5(request.POST.get("user_pass").encode()).hexdigest()
        user.nick_name = request.POST.get("nick_name")
        user.user_icon = request.POST.get("user_icon")
        user.save()
        return JsonResponse(Res.success(None))
    else:
        return JsonResponse(Res.error(500, '用户已存在'))


# 更新用户
@csrf_exempt
def update(request):
    if request.POST.get("id") != '1':
        user = SystemUser.objects.filter(id=request.POST.get("id")).first()
        user.user_name = request.POST.get("user_name")
        if user.user_pass != request.POST.get("user_pass"):
            user.user_pass = hashlib.md5(bytes(request.POST.get("user_pass"), encoding="utf8")).hexdigest()
        user.nick_name = request.POST.get("nick_name")
        user.user_icon = request.POST.get("user_icon")
        user.save()
        return JsonResponse(Res.success(None))
    else:
        return JsonResponse(Res.error(500, '不允许操作超级管理员'))


# 更新用户头像
@csrf_exempt
def update_user_icon(request):
    res = {}
    if request.method == "POST":
        user_id = request.POST.get('id')
        user_icon = request.POST.get('img')
        user = SystemUser.objects.filter(id=user_id).first()
        if not (user is None):
            user.user_icon = user_icon
            # 保存
            user.save()
            request.session['admin_user'] = user.to_dict()
            return JsonResponse(Res.success(None))
        else:
            return JsonResponse(Res.error(403, '用户不存在'))


# 删除用户
def delete(request):
    id = request.GET.get("id")
    if id == '1':
        return JsonResponse(Res.error(500, '不允许删除超级管理员'))
    else:
        user = SystemUser.objects.filter(id=id).first()
        user.delete()
        return JsonResponse(Res.success(None))
